package com.itmuch.box.util;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

/**
 * 参考文档: http://home.bdqn.cn/thread-32140-1-1.html
 * @author zhouli
 */
public class OrikaUtil {
    /**
     * 将source 转换成 destinationClass
     * @param sourceObject 源对象
     * @param destinationClass 目标类
     * @return
     */
    public static <T> T map(Object sourceObject, Class<T> destinationClass) {
        MapperFacade mapper = getMapper(sourceObject.getClass(), destinationClass);
        return mapper.map(sourceObject, destinationClass);
    }

    /**
     * 将source 转换成destinationObject
     * @param sourceObject 源对象
     * @param destinationObject 目标对象
     */
    public static void map(Object sourceObject, Object destinationObject) {
        MapperFacade mapper = getMapper(sourceObject.getClass(), destinationObject.getClass());
        mapper.map(sourceObject, destinationObject);
    }

    /**
     * 获得mapper
     * @param sourceClass 源类
     * @param destinationClass 目标类
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static MapperFacade getMapper(Class sourceClass, Class destinationClass) {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        mapperFactory.classMap(sourceClass, destinationClass).mapNulls(false).mapNullsInReverse(false).byDefault().register();
        return mapperFactory.getMapperFacade();
    }
}
